﻿using Microsoft.Win32;
using PhonePcFileTransfer.Models;
using QRCoder;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace PhonePcFileTransfer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        private FileTransferServer _fileServer;
        private string _localIp;
        private int _port;
        private string _saveDirectory;
        public MainWindow()
        {
            InitializeComponent();
            InitializeSettings();
        }
        /// <summary>
        /// 初始化应用设置
        /// </summary>
        private void InitializeSettings()
        {
            // 设置默认保存路径（用户文档下的Transfer文件夹）
            _saveDirectory = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Transfer");
            SavePathTextBox.Text = _saveDirectory;

            // 创建保存目录（如果不存在）
            if (!Directory.Exists(_saveDirectory))
            {
                Directory.CreateDirectory(_saveDirectory);
            }

            // 加载保存目录中的文件到列表
            LoadFilesInDirectory();
        }
        /// <summary>
        /// 加载保存目录中的文件到列表
        /// </summary>
        private void LoadFilesInDirectory()
        {
            try
            {
                if (Directory.Exists(_saveDirectory))
                {
                    var files = Directory.GetFiles(_saveDirectory)
                        .Select(path => new FileInfoModel { Path = path })
                        .OrderByDescending(f => new FileInfo(f.Path).LastWriteTime)
                        .ToList();

                    FileListBox.ItemsSource = files;
                }
            }
            catch (Exception ex)
            {
                UpdateStatus($"加载文件列表失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取本地局域网IP地址
        /// </summary>
        private string GetLocalIpAddress()
        {
            try
            {
                var host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (var ip in host.AddressList)
                {
                    // 寻找IPv4地址且不是回环地址
                    if (ip.AddressFamily == AddressFamily.InterNetwork &&
                        !IPAddress.IsLoopback(ip)&&ip.ToString().StartsWith("192.168"))
                    {
                        return ip.ToString();
                    }
                }
                return "127.0.0.1"; // 回环地址作为 fallback
            }
            catch (Exception ex)
            {
                UpdateStatus($"获取IP地址失败: {ex.Message}");
                return "127.0.0.1";
            }
        }

        /// <summary>
        /// 获取可用端口
        /// </summary>
        private int GetAvailablePort()
        {
            try
            {
                // 使用TcpListener自动获取一个可用端口
                using (var listener = new TcpListener(IPAddress.Loopback, 0))
                {
                    listener.Start();
                    return ((IPEndPoint)listener.LocalEndpoint).Port;
                }
            }
            catch (Exception ex)
            {
                UpdateStatus($"获取可用端口失败: {ex.Message}");
                return 8080; // 默认端口作为 fallback
            }
        }

        /// <summary>
        /// 生成二维码图片
        /// </summary>
        private BitmapImage GenerateQrCode(string url)
        {
            try
            {
                using (var qrGenerator = new QRCodeGenerator())
                {
                    var qrCodeData = qrGenerator.CreateQrCode(url, QRCodeGenerator.ECCLevel.Q);
                    using (var qrCode = new QRCode(qrCodeData))
                    {
                        using (var bitmap = qrCode.GetGraphic(10))
                        {
                            using (var stream = new MemoryStream())
                            {
                                bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                                stream.Position = 0;

                                var bitmapImage = new BitmapImage();
                                bitmapImage.BeginInit();
                                bitmapImage.StreamSource = stream;
                                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                                bitmapImage.EndInit();
                                return bitmapImage;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                UpdateStatus($"生成二维码失败: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 更新状态信息
        /// </summary>
        private void UpdateStatus(string message)
        {
            // 确保在UI线程更新
            Dispatcher.Invoke(() =>
            {
                StatusTextBox.AppendText($"[{DateTime.Now:HH:mm:ss}] {message}\n");
                StatusTextBox.ScrollToEnd();
            });
        }

        /// <summary>
        /// 浏览保存路径按钮点击事件
        /// </summary>
        /// <summary>
        /// 浏览保存路径按钮点击事件（WPF原生方式）
        /// </summary>
        private void BrowseSavePath_Click(object sender, RoutedEventArgs e)
        {
            // 创建一个打开文件对话框，但配置为选择文件夹
            var dialog = new OpenFileDialog
            {
                Title = "选择文件保存目录",
                ValidateNames = false,
                CheckFileExists = false,
                CheckPathExists = true,
                FileName = "选择目录"
            };

            if (dialog.ShowDialog() == true)
            {
                string newDirectory = System.IO.Path.GetDirectoryName(dialog.FileName);
                _saveDirectory = newDirectory; // 更新MainWindow的变量
                SavePathTextBox.Text = _saveDirectory; // 更新UI显示

                // 2. 关键：同步到FileTransferServer（如果服务器已初始化）
                if (_fileServer != null)
                {
                    _fileServer.SetSaveDirectory(newDirectory); // 调用服务器的更新方法
                }
                else
                {
                    // 可选：如果服务器未启动，记录日志或提示
                    UpdateStatus("服务器未初始化，目录仅在本地更新");
                }

                // 3. 刷新电脑端显示的文件列表
                LoadFilesInDirectory();

                // 4. （可选）通知手机客户端刷新（如果已实现WebSocket）
                
            }
        }


        /// <summary>
        /// 启动/停止服务按钮点击事件
        /// </summary>
        private void StartServerBtn_Click(object sender, RoutedEventArgs e)
        {
            if (_fileServer == null || !_fileServer.IsRunning)
            {
                StartServer();
            }
            else
            {
                StopServer();
            }
        }

        /// <summary>
        /// 启动文件传输服务
        /// </summary>
        private void StartServer()
        {
            try
            {
                // 获取IP和端口
                _localIp = GetLocalIpAddress();
                _port = GetAvailablePort();

                // 创建并启动服务器
                _fileServer = new FileTransferServer(_saveDirectory, _localIp, _port);
                _fileServer.OnStatusChanged += UpdateStatus;
                _fileServer.OnTransferProgress += UpdateTransferProgress;
                _fileServer.Start();

                // 更新UI
                StartServerBtn.Content = "停止服务";
                CreateHotspotBtn.IsEnabled = true;

                // 显示连接信息
                var connectionUrl = $"http://{_localIp}:{_port}";
                ConnectionInfo.Text = $"本地地址:\n{connectionUrl}\n\n请确保手机与电脑在同一WiFi网络下";

                // 生成并显示二维码
                QrCodeImage.Source = GenerateQrCode(connectionUrl);

                UpdateStatus("服务已启动，等待连接...");
                UpdateStatus($"本地地址:\n{connectionUrl}\n\n请确保手机与电脑在同一WiFi网络下");
            }
            catch (Exception ex)
            {
                UpdateStatus($"启动服务失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 停止文件传输服务
        /// </summary>
        private void StopServer()
        {
            try
            {
                if (_fileServer != null)
                {
                    _fileServer.Stop();
                    _fileServer.OnStatusChanged -= UpdateStatus;
                    _fileServer.OnTransferProgress -= UpdateTransferProgress;
                    _fileServer = null;
                }

                // 更新UI
                StartServerBtn.Content = "启动服务";
                CreateHotspotBtn.IsEnabled = false;
                QrCodeImage.Source = null;
                ConnectionInfo.Text = "";
                UpdateStatus("服务已停止");
            }
            catch (Exception ex)
            {
                UpdateStatus($"停止服务失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新传输进度
        /// </summary>
        private void UpdateTransferProgress(string fileName, long transferred, long total)
        {
            Dispatcher.Invoke(() =>
            {
                if (total <= 0)
                {
                    TransferProgressBar.Visibility = Visibility.Collapsed;
                    ProgressText.Text = "";
                    return;
                }

                double percentage = (double)transferred / total * 100;
                TransferProgressBar.Visibility = Visibility.Visible;
                TransferProgressBar.Value = percentage;
                ProgressText.Text = $"正在传输: {fileName} ({transferred.FormatSize()}/{total.FormatSize()}) - {percentage:F1}%";
            });
        }

        /// <summary>
        /// 创建热点按钮点击事件
        /// </summary>
        private void CreateHotspotBtn_Click(object sender, RoutedEventArgs e)
        {
            var hotspotDialog = new HotspotDialog();
            if (hotspotDialog.ShowDialog() == true)
            {
                var ssid = hotspotDialog.Ssid;
                var password = hotspotDialog.Password;

                try
                {
                    var result = HotspotManager.CreateHotspot(ssid, password);
                    UpdateStatus(result ?
                        $"热点创建成功: {ssid}, 密码: {password}" :
                        "热点创建失败，请确保你的网卡支持虚拟WiFi");
                }
                catch (Exception ex)
                {
                    UpdateStatus($"创建热点时出错: {ex.Message}");
                }
            }
        }

        /// <summary>
        /// 发送文件按钮点击事件
        /// </summary>
        private void SendFileBtn_Click(object sender, RoutedEventArgs e)
        {
            if (_fileServer == null || !_fileServer.IsRunning)
            {
                UpdateStatus("请先启动服务");
                return;
            }

            var button = sender as Button;
            var filePath = button?.CommandParameter as string;

            if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
            {
                // 在实际实现中，这里应该通知所有连接的客户端有新文件可下载
                // 简化处理：只是更新状态
                UpdateStatus($"准备发送文件: {System.IO.Path.GetFileName(filePath)}");
            }
        }

        /// <summary>
        /// 窗口关闭时停止服务
        /// </summary>
        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            StopServer();
        }
    }
    ///// <summary>
    ///// 扩展方法：格式化文件大小
    ///// </summary>
    //public static class SizeFormatExtensions
    //{
    //    public static string FormatFileSize(this long bytes)
    //    {
    //        if (bytes < 1024)
    //            return $"{bytes} B";
    //        else if (bytes < 1048576)
    //            return $"{(bytes / 1024.0).ToString("0.0")} KB";
    //        else if (bytes < 1073741824)
    //            return $"{(bytes / 1048576.0).ToString("0.0")} MB";
    //        else
    //            return $"{(bytes / 1073741824.0).ToString("0.0")} GB";
    //    }
    //}
}